package com.sanshengshui.iot.test;

import io.netty.channel.EventLoop;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.util.concurrent.DefaultPromise;
import io.netty.util.concurrent.GenericFutureListener;
import io.netty.util.concurrent.Promise;

import java.time.LocalDateTime;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class FutureAndPromiseDemo {
    public static void main(String[] args) throws Exception{

        ExecutorService executor = Executors.newFixedThreadPool(2);
        Future<String> future = executor.submit(new Callable<String>() {
            @Override
            public String call() throws Exception {
                Thread.sleep(1000);
                return "result,"+ LocalDateTime.now();
            }
        });
        System.out.println(future.get());

        // netty future
        NioEventLoopGroup eventExecutors = new NioEventLoopGroup();
        EventLoop eventLoop = eventExecutors.next();
        // io.netty.channel.nio.NioEventLoop
        System.out.println("eventLoop.class="+eventLoop.getClass());
        io.netty.util.concurrent.Future<String> nettyfuture = eventLoop.submit(new Callable<String>() {
            @Override
            public String call() throws Exception {
                Thread.sleep(1000);
                return "netty_future_result_"+LocalDateTime.now();
            }
        });

        nettyfuture.addListener(new GenericFutureListener<io.netty.util.concurrent.Future<? super String>>() {
            @Override
            public void operationComplete(io.netty.util.concurrent.Future<? super String> future) throws Exception {
                // get or getNow
                System.out.println(future.getNow());
            }
        });

        System.out.println(LocalDateTime.now());
        Thread.sleep(2000);

        //  promise
        Promise<String> promise = new DefaultPromise<>(eventLoop);
        // Promise<String> promise = new DefaultPromise<>();

        new Thread(()->{
            try {
                Thread.sleep(1000);
                promise.setSuccess("netty_promise_result_"+LocalDateTime.now());
            } catch (Exception e) {
                promise.setFailure(e);
            }
        }).start();
        System.out.println(LocalDateTime.now());
        System.out.println(promise.get());
    }
}
